package com.learn.springboot3.jwt;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: Jwt
 * Package: com.learn.springboot3.jwt
 * Description:
 *
 * @Author jiangCheng
 * @Create 2024/10/22 9:37
 * @Version 1.0
 */
@Component
public class Jwt {

        private String SECRET_KEY = "your_secret_key"; // 请更改为一个安全的密钥

        public String generateToken(String username) {
            Map<String, Object> claims = new HashMap<>();
            return createToken(claims, username);
        }

        private String createToken(Map<String, Object> claims, String subject) {
            return Jwts.builder()
                    .setClaims(claims)
                    .setSubject(subject)
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10小时过期
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                    .compact();
        }

        public Boolean validateToken(String token, String username) {
            final String extractedUsername = extractUsername(token);
            return (extractedUsername.equals(username) && !isTokenExpired(token));
        }

        private String extractUsername(String token) {
            return extractAllClaims(token).getSubject();
        }

        private Claims extractAllClaims(String token) {
//            return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
            return null;
        }

        private Boolean isTokenExpired(String token) {
            return extractAllClaims(token).getExpiration().before(new Date());
        }


}
